#include "pch.h"
#include "MaterialLibrary.h"
#include <memory.h>

#define _MATERIAL_LIBRARY_GROW_THRESHOLD_ 90
#define _MATERIAL_LIBRARY_SHRINK_THRESHOLD_ 90
#define _MATERIAL_LIBRARY_GROW_PERCENT_ 20
#define _MAX_GROW_SIZE 20
#define _MIN(x,y) ((x) < (y) ? (x) : (y))

#define _GROW_BY_PERCENT(x,p)  ((((x) * (p)) + (x)) / (p))

MaterialLibrary::MaterialLibrary()
{
	// The initial size of the Material Library is 4.
	size = 20;

	// Allocate space to the library so it is ready to receive
	// new data.
	materials = (Material**)malloc(sizeof(Material*) * size);
}

MaterialLibrary::~MaterialLibrary()
{
	for(int i = 0; i < this->count; i ++)
	{
		free(materials[i]);
	}

	free(materials);

	size = 0;
	count = 0;
}

// Adds a material to the libray and returns 
int MaterialLibrary::Add(Material* material)
{
	int countAfterAdd = 
		this->count + 1;

	// test if the number of items inside the library is approaching 90%
	// of the library's internal buffer, if so reallocate more space to
	// fill the library.
	int percentageFilled =
		(countAfterAdd * 100) / size;

	if (percentageFilled > _MATERIAL_LIBRARY_GROW_THRESHOLD_)
	{
		// the new size should grow by 10%
		int newSize = _MIN( _GROW_BY_PERCENT(size, _MATERIAL_LIBRARY_GROW_PERCENT_), (size + _MAX_GROW_SIZE));
			
		materials = (Material**)realloc(materials, newSize);

		// Set the new size of the material library
		this->size = newSize;
	}

	// Add the material to the library
	materials[this->count] = material;
	// and store the index the material was added at so it can be returned.
	int materialIndex = this->count;

	// Set the new Count
	this->count = countAfterAdd;

	// return the index the material was added at.
	return materialIndex;
}

// Removes a material from the libray - DOESN'T DO ANYTHING YET!!!
void MaterialLibrary::Remove(Material* material)
{
}

// Get the material from the library given the Material ID
Material* MaterialLibrary::GetMaterial(int MaterialID)
{
	return materials[MaterialID];
}